#include "commonfunction.h"
#include "systempreset.h"
#include <QDateTime>
#include <QDir>
#include <QDebug>
#include <QDesktopWidget>
#include <QApplication>
#include <QRegExp>

QString currentDateTime()
{
    QDateTime datetime = QDateTime::currentDateTime();
    QString dt = datetime.toString("yyyy-MM-dd hh:mm:ss");
    return dt;
}

Role initRole()
{
    Role r;
    r.name = "";
    r.permission = 0;
    r.createDatetime = currentDateTime();
    return r;
}

QString convertMillSec2Sec(QString currDT)
{
    QDateTime datetime = QDateTime::fromString(currDT, "yyyy-MM-dd hh:mm:ss.zzz");
    QString dt = datetime.toString("yyyy-MM-dd hh:mm:ss");
    return dt;
}

QString currentDateTimeMS()
{
    QDateTime datetime = QDateTime::currentDateTime();
    QString dt = datetime.toString("yyyy-MM-dd hh:mm:ss.zzz");
    return dt;
}

bool createDir(QString path)
{
    bool ret = false;
    QDir dir;
    if(dir.exists(path))
    {
        qDebug() << "dir" << path << "exist";
        ret = true;
    }
    else {
        ret = dir.mkdir(path);
        qDebug() << "mkdir ret = " << ret;
    }
    return ret;
}

void setWidgetCenter(QWidget *w)
{
    QDesktopWidget *desktop = QApplication::desktop();
    w->move((desktop->width() - w->width())/ 2, (desktop->height() - w->height()) /2);
    w->show();
}

bool openTextByIODevice(const QString FileName,QString line)
{
    QFile file(FileName);
    file.open(QIODevice::WriteOnly | QIODevice::Text);
    file.write(line.toUtf8());
    file.close();

    return  true;
}

QStringList getPicFileNameList(const QString & path)
{
    QDir dir;
    dir.setPath(path);
    QStringList nameFilters;
    nameFilters << "*.jpg" << "*.png";
    dir.setFilter(QDir::Files|QDir::Readable);
    dir.setSorting(QDir::Name);
    QFileInfoList fileInfolist = dir.entryInfoList(nameFilters);
    QStringList fullNameList;
    int count = fileInfolist.count();
    for (int i =0;i < count;i++) {
        fullNameList.append(fileInfolist[i].absoluteFilePath());
    }
    return fullNameList;
}

bool checkIPValid(const QString &addr)
{
    //check if ip valid
    QRegExp regExp("((2[0-4]\\d|25[0-5]|[01]?\\d\\d?)\\.){3}(2[0-4]\\d|25[0-5]|[01]?\\d\\d?)");
    return regExp.exactMatch(addr);
}

QString generateFileName(const QString & dir, const QString &prefix, const QString &suffix)
{
    QDateTime datetime = QDateTime::currentDateTime();
    QString dt = datetime.toString("yyyyMMdd_hhmmss_zzz");
    QString fileName = dir + QString("%1_%2.%3").arg(prefix).arg(dt).arg(suffix);
    return fileName;
}

qint64 timeDiffSecond(QDateTime dt1, QDateTime dt2)
{
    qint64 diff = dt1.secsTo(dt2);
    return diff;
}

bool checkPwValid(const QString &pw)
{
    bool isValid = false;
    if (pw.length() >= MIN_PASSWORD_LENGTH &&
        pw.length() <= MAX_PASSWORD_LENGTH &&
        pw.contains(QRegExp("[0-9]{1,}")) &&
        pw.contains(QRegExp("[a-z]{1,}")) &&
        pw.contains(QRegExp("[A-Z]{1,}")))
    {
        isValid = true;
    }

    return isValid;
}

bool checkPwSimple(const QString &pw)
{
    bool isSimple = false;
    if(pw == USER_INIT_PASSWORD)
    {
        isSimple = true;
    }

    return isSimple;
}

int random(int min, int max)
{
    qsrand(QTime(0, 0, 0).secsTo(QTime::currentTime()));
    int num = qrand() % (max - min);
    return num + min;
}

bool doubleEquals(double d1, double d2)
{
    return qAbs(d1 - d2) < DOUBLE_PRECISION;
}

bool doubleGreater(double d1, double d2)
{
    return (d1 - d2) > DOUBLE_PRECISION;
}

QString doubleToString(double d, int n)
{
    return QString::number(QString::number(d, 'f', n).toDouble(), 'f', QLocale::FloatingPointShortest);
}

/**
 * @brief predictRuntimes 计算预计电转时间
 * @param liquidVolume 体积，单位：ml
 * @param flowRate 流速，单位：ml/min
 * @return 预计实验时长，单位：s
 */
quint64 predictRuntimes(double liquidVolume, double flowRate)
{
    const double pipeVolume = 8.62; // 管路体积
    quint64 duration = 60 * 30; // 默认30分钟

    double flowRateCalib = flowRate;
    double ratio = SystemPreset::instance()->getDoubleData(EnumPresetItem::FlowRateCalibCoef);
    ratio = (ratio > DOUBLE_PRECISION) ? ratio : 1.0; // 流速校准系数
    flowRateCalib = flowRateCalib * ratio;

    if (liquidVolume > DOUBLE_PRECISION && flowRate > DOUBLE_PRECISION)
    {
        duration = qRound((liquidVolume + pipeVolume) / flowRateCalib * 60) + 30;
    }

    return duration;
}
